package com.example.abc.util;

import com.example.abc.dto.MyUserDetails;
import com.example.abc.websocket.OnlineUsers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by Peter on 2018/5/8.
 */
@Component
public class SessionUtils {
    public static final Logger logger = LoggerFactory.getLogger(SessionUtils.class);
    @Autowired
    private SessionRegistry sessionRegistry;

    public void expireUserSessions(String username) {
        List<Object> principalList = sessionRegistry.getAllPrincipals();
        logger.info("AllPrincipals size is " + principalList.size());

        for (Object principal : sessionRegistry.getAllPrincipals()) {
            if (principal instanceof MyUserDetails) {
                MyUserDetails userDetails = (MyUserDetails) principal;
                if (userDetails.getUsername().equals(username)) {
                    List<SessionInformation> list = sessionRegistry.getAllSessions(userDetails, true);
                    logger.error(username + " set to expired. session size is:" + list.size());
                    for (SessionInformation information : list) {
                        information.expireNow();
                        logger.error(information.getSessionId() + " set to expired.");
                    }
                }
            } else {
                logger.error("principal is not MyUserDetails type...............");
            }
        }
    }
}
